package myJs.components.pure

import japgolly.scalajs.react._
import japgolly.scalajs.react.component.Scala.BackendScope
import japgolly.scalajs.react.extra.StateSnapshot
import japgolly.scalajs.react.vdom.all._
import myJs.Implicits._
import myJs.Utils._
import myJs.myPkg.jquery._

/**
 * Created by yz on 3/11/2020
 */
object TogglePureComponent {

  case class Props(state: StateSnapshot[Boolean],name: String, fieldName: String = "",
                   questionInfo: String = "", show: Boolean = true) {
    @inline def render: VdomElement = Component(this)
  }

  class Backend(bs: BackendScope[Props, Unit]) {

    def render(p: Props) = {

      def toggleValid(toggleShow: Boolean, fieldName: String) = Callback {
        val bv = $("#form").bv
        val node = ReactDOM.findDOMNode(bs.raw).get.node
        val parentJq = $(node).parents(".myArg")
        if (fieldName.nonBlank) {
          val curJq = parentJq.findInputByName(fieldName)
          if (toggleShow) {
            bv.revalidateField(curJq)
          } else {
            bv.updateStatus(curJq, "VALID")
          }
        }
      }

      def defaultChange(checked: Boolean)(e: ReactEventFromInput) = {
        toggleValid(checked, p.fieldName) >>
          p.state.modState(x => checked)
      }

      val s = p.state.value
        div(`class` := s"toggle btn ${if (s) "btn-primary" else "btn-light off"}",
          vDataToggle := "toggle", role := "button", width := "53px", height := "34px",
          input(`class` := "", `type` := "checkbox", (checked := true).when(s),
            vDataToggle := "toggle", vDataOn := "是", vDataOff := "否", name := s"${p.name}",
            vDataId := "iPathContent",
            `class` := "", width := "100px", value := "true"),
          div(`class` := "toggle-group",
            label(`for` := "", `class` := "btn btn-primary toggle-on", "是", onClick ==> defaultChange(false)),
            label(`for` := "", `class` := "btn btn-light toggle-off", "否", onClick ==> defaultChange(true)),
            span(`class` := "toggle-handle btn btn-light")
          )
        )
    }
  }

  val Component = ScalaComponent.builder[Props].renderBackend[Backend].
    build

}



